import urllib, simplejson

DEFAULT_FROM_LANGUAGE = 'en'
DEFAULT_TO_LANGUAGE = 'en'

TRANSLATE_URL = 'http://ajax.googleapis.com/ajax/services/language/translate?'
TRANSLATE_PARAMS = {'v':'1.0', 'q':'', 'langpair': '',}

DETECT_URL = 'http://ajax.googleapis.com/ajax/services/language/detect?'
DETECT_PARAMS = {'v':'1.0', 'q':'', }

LANGUAGES = [('', 'Unknown'), ('af', 'Afrikaans'), ('sq', 'Albanian'),
        ('am', 'Amharic'), ('ar', 'Arabic'), ('hy', 'Armenian'),
        ('az', 'Azerbaijani'), ('eu', 'Basque'), ('be', 'Belarusian'),
        ('bn', 'Bengali'), ('bh', 'Bihari'), ('bg', 'Bulgarian'),
        ('my', 'Burmese'), ('ca', 'Catalan'), ('chr', 'Cherokee'),
        ('zh', 'Chinese'), ('zh-CN', 'Chinese_simplified'),
        ('zh-TW', 'Chinese_traditional'), ('hr', 'Croatian'),
        ('cs', 'Czech'), ('da', 'Danish'), ('dv', 'Dhivehi'),
        ('nl', 'Dutch'), ('en', 'English'), ('eo', 'Esperanto'),
        ('et', 'Estonian'), ('tl', 'Filipino'), ('fi', 'Finnish'),
        ('fr', 'French'), ('gl', 'Galician'), ('ka', 'Georgian'),
        ('de', 'German'), ('el', 'Greek'), ('gn', 'Guarani'),
        ('gu', 'Gujarati'), ('iw', 'Hebrew'), ('hi', 'Hindi'),
        ('hu', 'Hungarian'), ('is', 'Icelandic'), ('id', 'Indonesian'),
        ('iu', 'Inuktitut'), ('it', 'Italian'), ('ja', 'Japanese'),
        ('kn', 'Kannada'), ('kk', 'Kazakh'), ('km', 'Khmer'),
        ('ko', 'Korean'), ('ku', 'Kurdish'), ('ky', 'Kyrgyz'),
        ('lo', 'Laothian'), ('lv', 'Latvian'), ('lt', 'Lithuanian'),
        ('mk', 'Macedonian'), ('ms', 'Malay'), ('ml', 'Malayalam'),
        ('mt', 'Maltese'), ('mr', 'Marathi'), ('mn', 'Mongolian'),
        ('ne', 'Nepali'), ('no', 'Norwegian'), ('or', 'Oriya'),
        ('ps', 'Pashto'), ('fa', 'Persian'), ('pl', 'Polish'),
        ('pt-PT', 'Portuguese'), ('pa', 'Punjabi'), ('ro', 'Romanian'),
        ('ru', 'Russian'), ('sa', 'Sanskrit'), ('sr', 'Serbian'),
        ('sd', 'Sindhi'), ('si', 'Sinhalese'), ('sk', 'Slovak'),
        ('sl', 'Slovenian'), ('es', 'Spanish'), ('sw', 'Swahili'),
        ('sv', 'Swedish'), ('tg', 'Tajik'), ('ta', 'Tamil'),
        ('te', 'Telugu'), ('th', 'Thai'), ('bo', 'Tibetan'),
        ('tr', 'Turkish'), ('ug', 'Uighur'), ('uk', 'Ukrainian'),
        ('ur', 'Urdu'), ('uz', 'Uzbek'), ('vi', 'Vietnamese')
        ]

def translate(sentence,
        from_lang=DEFAULT_FROM_LANGUAGE,
        to_lang=DEFAULT_TO_LANGUAGE,
        full_return=False,
        ):
    """Connect to the google translator API and get translation of the sentence"""
    params = TRANSLATE_PARAMS.copy()
    params['q'] = sentence
    params['langpair'] = '|'.join([from_lang, to_lang])

    # Concatenated the full URL
    url = TRANSLATE_URL + urllib.urlencode(params)

    # Get translation from the API server
    fp = urllib.urlopen(url)
    resp = fp.read()
    fp.close()

    # Converts to JSON
    resp = simplejson.loads(resp)

    if full_return:
        return resp

    if resp['responseStatus'] == 200:
        try:
            return resp['responseData']['translatedText'].encode('utf-8')
        except:
            pass
    else:
        raise Exception('(%(responseStatus)s) %(responseDetails)s'%resp)
    
    return None

def detect_language(sentence, full_return=False):
    """Uses feature of API to detect what is the language of the sentence"""
    params = DETECT_PARAMS.copy()
    params['q'] = sentence

    # Concatenated the full URL
    url = DETECT_URL + urllib.urlencode(params)

    # Get translation from the API server
    fp = urllib.urlopen(url)
    resp = fp.read()
    fp.close()

    # Converts to JSON
    resp = simplejson.loads(resp)

    if full_return:
        return resp

    if resp['responseStatus'] == 200:
        try:
            return resp['responseData']['language']
        except:
            pass
    else:
        raise Exception('(%(responseStatus)s) %(responseDetails)s'%resp)
    
    return None

